package com.crazy.jiakoulachang.aop;

import com.alibaba.excel.util.StringUtils;
import com.crazy.jiakoulachang.annotation.AuthCheck;
import com.crazy.jiakoulachang.exception.ExceptionEnum;
import com.crazy.jiakoulachang.exception.MallException;
import com.crazy.jiakoulachang.pojo.Role;
import com.crazy.jiakoulachang.service.RoleService;
import com.sun.xml.internal.ws.client.ResponseContext;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.soap.AddressingFeature;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: lhy-卢辉宇
 * @date: 2023/6/26 21:27
 * @description: 权限校验aop
 */
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private RoleService roleService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //获取注解传入的描述数组转换喂List集合
        List<String> anyRole = Arrays.stream(authCheck.anyRole()).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 当前登录用户
       Role role= roleService.getLoginRole(request);
        // 拥有任意权限即通过
        if (CollectionUtils.isNotEmpty(anyRole)) {
            String userRole = role.getUserRole();
            if (!anyRole.contains(userRole)) {
                throw new MallException(ExceptionEnum.NO_AUTH_ERROR);
            }
        }
        // 必须有所有权限才通过
        if (StringUtils.isNotBlank(mustRole)) {
            String userRole = role.getUserRole();
            if (!mustRole.equals(userRole)) {
                throw new MallException(ExceptionEnum.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
            return joinPoint.proceed();

    }
}
